const randomInt = require('./randomInt');
const getQueryStringFromParams = require('./getQueryStringFromParams');
const getSignature = require('./getSignature');
const axios = require('axios/index');

class ApigwClient {
    constructor(clientID, clientSecret){
        this.clientID=clientID;
        this.clientSecret=clientSecret
    }
    request({url, method, params = {},headers={}}){
        const path = new URL(url).pathname;
        const headersAppend = {
            'Content-Type': 'application/json',
            'X-Api-ClientID': this.clientID,
            'X-Api-Auth-Version': "2.0",
            'X-Api-TimeStamp': Date.now(),
            'X-Api-SignHeaders': 'X-Api-TimeStamp,X-Api-Nonce',
            'X-Api-Nonce': randomInt(),
            'X-Api-Signature': '',

        }

        const queryString = getQueryStringFromParams(params);
        headersAppend['X-Api-Signature'] = getSignature( path, method, headersAppend, queryString, this.clientSecret )

        let fetchUrl
        if (queryString.length===0) {
            fetchUrl = url
        } else {
            fetchUrl = url + "?" + queryString
        }

        return axios.request({
            url:fetchUrl,
            method:method,
            headers:{
                ...headersAppend,
                ...headers
            }
        })
    }
}

module.exports = ApigwClient;
